<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-form-item label="单号" prop="requestNumber">
          <el-input v-model="queryParams.requestNumber" placeholder="请输入单号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="申请时间" style="width: 308px">
          <el-date-picker v-model="daterangeRequestDate" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
            range-separator="-" start-placeholder="开始日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"></el-date-picker>
        </el-form-item>
        <el-form-item label="预期交货时间" style="width: 308px">
          <el-date-picker v-model="daterangeExpectedDeliveryDate" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
            range-separator="-" start-placeholder="开始日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"></el-date-picker>
        </el-form-item>
        <el-form-item label="采购状态" prop="purchaseStatus">
          <el-select v-model="queryParams.purchaseStatus" placeholder="请选择采购状态" clearable>
            <el-option v-for="dict in wms_purchase_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt20">

      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">采购申请</span></el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:purchaseRequests:add']">新增
          </el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport"
            v-hasPermi="['wms:purchaseRequests:export']">导出
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="purchaseRequestsList" border class="mt20">
        <el-table-column label="单号" prop="requestNumber" />
        <el-table-column label="仓库" prop="warehouseName" />
        <el-table-column label="库区" prop="areaName" />
        <el-table-column label="采购人" prop="requesterName" />
        <el-table-column label="供货商" prop="merchantName" />
        <el-table-column label="申请时间" align="center" prop="requestDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预期交货时间" align="center" prop="expectedDeliveryDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expectedDeliveryDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="采购状态" prop="purchaseStatus">
          <template #default="scope">
            <dict-tag :options="wms_purchase_status" :value="scope.row.purchaseStatus" />
          </template>
        </el-table-column>
        <el-table-column label="订单金额" prop="payableAmount" />
        <el-table-column label="商品总数" prop="totalQuantity" />
        <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="操作" align="right" class-name="small-padding fixed-width">
          <template #default="scope">

            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-if="scope.row.purchaseStatus==1">修改
            </el-button>

            <el-button link type="primary" icon="Edit" @click="toAudit(scope.row.id)" v-if="scope.row.purchaseStatus==1"
              v-hasPermi="['wms:purchaseRequests:edit']">审核
            </el-button>

            <el-button link type="primary" icon="Edit" @click="tobound(scope.row.id)"
              v-if="scope.row.purchaseStatus==2">入库
            </el-button>



            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['wms:purchaseRequests:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row>
        <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-row>

    </el-card>
  </div>
</template>

<script setup name="PurchaseRequests">
  import {
    listPurchaseRequests,
    getPurchaseRequests,
    delPurchaseRequests,
    addPurchaseRequests,
    updatePurchaseRequests,
    inboundPurchaseRequests,
    auditPurchaseRequests
  } from "@/api/wms/purchaseRequests";
  import { useWmsStore } from "@/store/modules/wms"
  const { proxy } = getCurrentInstance();
  const { wms_purchase_status } = proxy.useDict('wms_purchase_status');
  const purchaseRequestsList = ref([]);
  const open = ref(false);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const ids = ref([]);
  const total = ref(0);
  const title = ref("");
  const daterangeRequestDate = ref([]);
  const daterangeExpectedDeliveryDate = ref([]);

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      requestNumber: undefined,
      requestDate: undefined,
      expectedDeliveryDate: undefined,
      purchaseStatus: undefined,
    },
    rules: {
      warehouseId: [
        { required: true, message: "仓库ID不能为空", trigger: "blur" }
      ],
      areaId: [
        { required: true, message: "库区id不能为空", trigger: "blur" }
      ],
      requesterId: [
        { required: true, message: "采购人ID不能为空", trigger: "blur" }
      ],
      merchantId: [
        { required: true, message: "供货商ID不能为空", trigger: "blur" }
      ],
      purchaseStatus: [
        { required: true, message: "采购状态不能为空", trigger: "change" }
      ],
      remark: [
        { required: true, message: "备注不能为空", trigger: "blur" }
      ]
    },
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询采购申请列表 */
  function getList() {
    loading.value = true;
    queryParams.value.params = {};
    if (null != daterangeRequestDate && '' != daterangeRequestDate) {
      queryParams.value.params["beginRequestDate"] = daterangeRequestDate.value[0];
      queryParams.value.params["endRequestDate"] = daterangeRequestDate.value[1];
    }
    if (null != daterangeExpectedDeliveryDate && '' != daterangeExpectedDeliveryDate) {
      queryParams.value.params["beginExpectedDeliveryDate"] = daterangeExpectedDeliveryDate.value[0];
      queryParams.value.params["endExpectedDeliveryDate"] = daterangeExpectedDeliveryDate.value[1];
    }
    listPurchaseRequests(queryParams.value).then(response => {
      response.rows.forEach(item => {
        item.warehouseName = useWmsStore().warehouseList.filter(it => it.id === item.warehouseId)[0].warehouseName
        item.areaName = useWmsStore().areaList.filter(it => it.id === item.areaId)[0].areaName
        item.requesterName = item.requesterId
        item.merchantName = useWmsStore().merchantList.filter(it => it.id === item.merchantId)[0].merchantName
      });
      purchaseRequestsList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
      id: null,
      requestNumber: null,
      warehouseId: null,
      areaId: null,
      requesterId: null,
      merchantId: null,
      requestDate: null,
      expectedDeliveryDate: null,
      purchaseStatus: null,
      payableAmount: null,
      totalQuantity: null,
      createTime: null,
      updateTime: null,
      createBy: null,
      updateBy: null,
      remark: null
    };
    proxy.resetForm("purchaseRequestsRef");
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    daterangeRequestDate.value = [];
    daterangeExpectedDeliveryDate.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
  }

  /** 新增按钮操作 */
  function handleAdd() {
    proxy.$router.push({ path: "/purchaseEdit", query: { type: '0' } });
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    proxy.$router.push({ path: "/purchaseEdit", query: { id: row.id, type: '1' } });
  }

  /** 审核 */
  function toAudit(id) {
    proxy.$modal.confirm('是否确认提交审核').then(function () {
      loading.value = true;
      return auditPurchaseRequests(id);
    }).then(() => {
      loading.value = true;
      getList();
      proxy.$modal.msgSuccess("审核成功");
    }).catch(() => {
    }).finally(() => {
      loading.value = false;
    });
  }

  /** 入库 */
  function tobound(id) {
    proxy.$modal.confirm('是否确认提交入库').then(function () {
      loading.value = true;
      return inboundPurchaseRequests(id);
    }).then(() => {
      loading.value = true;
      getList();
      proxy.$modal.msgSuccess("入库成功");
    }).catch(() => {
    }).finally(() => {
      loading.value = false;
    });
  }
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["purchaseRequestsRef"].validate(valid => {
      if (valid) {
        form.value.purchaseRequestsDetails = form.value.detailsVos
        buttonLoading.value = true;
        if (form.value.id != null) {
          updatePurchaseRequests(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          }).finally(() => {
            buttonLoading.value = false;
          });
        } else {
          addPurchaseRequests(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          }).finally(() => {
            buttonLoading.value = false;
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除采购申请编号为"' + _ids + '"的数据项？').then(function () {
      loading.value = true;
      return delPurchaseRequests(_ids);
    }).then(() => {
      loading.value = true;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    }).finally(() => {
      loading.value = false;
    });
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('wms/purchaseRequests/export', {
      ...queryParams.value
    }, `purchaseRequests_${new Date().getTime()}.xlsx`)
  }

  const handleChangeWarehouse = (e) => {
    form.value.areaId = undefined
  }

  getList();
</script>